package com.flying.cattle.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @program: service
 * @description:
 * @author: nxw
 * @create: 2019-07-12 11:02
 **/
@Configuration
public class RedisConfigurtion {

    @Bean
    public ReactiveRedisTemplate<String, Object> reactiveJsonPostRedisTemplate(
            ReactiveRedisConnectionFactory connectionFactory,RedisSerializer<Object> redisSerializer) {
        RedisSerializationContext<String, String> string = RedisSerializationContext.string();
        RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
                .<String, Object>newSerializationContext(new StringRedisSerializer())
                .key(string.getKeySerializationPair())
                .hashKey(string.getKeySerializationPair())
                .hashValue(string.getKeySerializationPair())
                .value(redisSerializer)
                .build();


        return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
    }

    @Bean
    public  RedisSerializer<Object> genericJackson2JsonRedisSerializer() {
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        return serializer;
    }


}
